package com.group10.service.impl;

import com.group10.entity.Result;
import com.group10.mapper.BlogMapper;
import com.group10.mapper.LikeMapper;
import com.group10.mapper.ShowMapper;
import com.group10.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.group10.util.TimeUtil.getNow;

@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private ShowMapper showMapper;
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private UserServiceImpl userService;

    @Override
    public Result<?> insertLike(String token, String topic, Integer likeId) {
        String userId = (String) userService.userInfo(token).get("id");
        if (likeMapper.insertLike(topic,userId,likeId,getNow()) > 0){
//            return Result.success();
            if (topic.equals("show")){
                if(showMapper.likeShow(likeId) > 0){
                    return Result.success();
                }else {
                    return Result.error("点赞异常，在更新show表时出错");
                }
            }else if(topic.equals("blog")){
                if(blogMapper.likeBlog(likeId) > 0){
                    return Result.success();
                }else {
                    return Result.error("点赞异常，在更新blog表时出错");
                }
            }else{
                return Result.error("不存在的点赞类型");
            }
        }else{
            return Result.error("点赞异常，在更新likes表时出错");
        }
    }

    @Override
    public Result<?> isLike(String token, String topic, Integer likeId) {
        String userId = (String) userService.userInfo(token).get("id");
        if (likeMapper.isLike(topic,userId,likeId) > 0){
            return Result.success(true);
        }else{
            return Result.success(false);
        }
    }

    @Override
    public Result<?> getCount(String topic, Integer likeId) {
        return Result.success(likeMapper.getCount(topic,likeId));
    }

    @Override
    public Result<?> deleteLike(String token,String topic, Integer likeId) {
        String userId = (String) userService.userInfo(token).get("id");
        if (likeMapper.deleteLike(topic,userId,likeId) > 0){
            try{
                showMapper.unLikeShow(likeId);
            }catch (Exception e){
                return Result.error("取消点赞异常");
            }

            return Result.success();
        }else{
            System.out.println(userId + topic + likeId);
            return Result.error("取消点赞异常");
        }
    }
}
